<?php
/**
* Mapping for a single related model
* 
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* 
* @copyright Copyright (c) 2008-2009 Ne8, LLC <josh.ribakoff@gmail.com>
* @license New BSD License
* @version 0.1
* @category Shuffler
* @package Shuffler_Mapper
* @subpackage Mapping
*/
class Shuffler_Mapper_Mapping_Single extends Shuffler_Mapper_Mapping
{
    
    protected $fieldIsInline = true;
    
    /**
    * Setter strategy for Shuffler_Mapper->doLoad()
    * 
    * @param Shuffler_Model to inject data into
    * @return Shuffler_Model after injecting data
    */
    protected function doLoad( Shuffler_Model $model, array $rs )
    {
        $id = (int)$this->getRowField( $rs, $this->getAliasedField() );
        $value = $this->getTargetMapper()->find( $id );
        $command = $this->getMutatorMethod(); 
        
        if( method_exists( $model, $command ) )
        {
            $model->$command( $value ); 
        }
        else
        {
            $property = $this->getProperty();
            $model->$property = $value;
        }
        return $model;
    }
    
    /*
    protected function doAggressiveLoad()
    {
        $value = $this->getTargetMapper()->loadRow( $id, $rs );
        if( is_null( $value ) )
        {
            throw new Exception( 'Cannot lookup foreign value' );
        }        
    } */
    
    protected function doGetFieldValue( $val )
    {
        return $val->getId(); 
    }
    
    public function select( $select ) 
    {
        /*$table = $this->getTargetMapper()->getTableName();
        $select->joinLeft(
            $table,
            $table . '.id = ' . $this->getTableName() . '.' . $this->getField(),
            $this->getSelectCols(),
            $this->getTargetMapper()->getSchemaName()
        );*/      
        return $select;
    }
    
    protected function getSelectCols()
    {
        $fields = array();
        foreach( $this->getTargetMapper()->getFields() as $k => $v )
        {
            $fields[ strtolower( $this->getProperty() ) . '_' . $v ] = $v;
        }
        return $fields;
    }
    
    /**
    * Get the name of the table for this mapping
    * 
    * @return string name of table
    */
    public function getTableName()
    {
         return $this->sourceMapper->getTableName();
    }
    
    public function getType()
    {
        return 'single';   
    }

}